import React, { Component } from 'react';
import '../assets/css/todomvc-common.css';
import '../assets/css/todomvc-app.css';

const stateList = ['All', 'Active', 'Completed'];

class TodoMVC extends Component {
  // 省去 constructor 是因为babel配置语法可以这样写，正常还是要使用constructor
  state = {
    todoList: JSON.parse(window.localStorage.getItem('todoList') || '[]'),
    currentItem: null,
    oldItem: null,
    currentState: window.localStorage.getItem('currentState') || 'All'
  }
  componentDidUpdate(prevProps, prevStates) {
    window.localStorage.setItem('todoList', JSON.stringify(prevStates.todoList));
    window.localStorage.setItem('currentState', prevStates.currentState);
    if (this.refs.inputOnFocus) {
      this.refs.inputOnFocus.focus();
    }
  }
  get leftCount () {
    return this.state.todoList.filter(t => !t.selected).length;
  }
  get someSelected () {
    return this.state.todoList.some(t => t.selected);
  }
  get allSelected () {
    return this.state.todoList.every(t => t.selected);
  }
  set allSelected (val) {
    let arr = [...this.state.todoList];
    arr.forEach((item) => {
      item.selected = val;
    });
    this.setState({ todoList: arr });
  }
  get list () {
    if (this.state.currentState === 'All') {
      return this.state.todoList;
    }
    if (this.state.currentState === 'Active') {
      return this.state.todoList.filter(t => !t.selected)
    }
    return this.state.todoList.filter(t => t.selected)
  }

  addList = (e) => {
    if (e.keyCode === 13 && e.target.value.trim() !== '') {
      const { todoList } = this.state;
      let last = todoList[todoList.length - 1];
      todoList.push({
        id: last ? last.id + 1 : 1,
        content: e.target.value.trim(),
        selected: false
      });
      this.setState({ todoList });
      e.target.value = '';
    }
  }
  itemChange = (e, item) => {
    const arr = [...this.state.todoList];
    arr.forEach((t) => {
      if (t.id === item.id) {
        t.selected = !t.selected;
      }
    })
    this.setState({ todoList: arr });
  }
  dblClick = (item) => {
    this.setState({
      currentItem: item,
      oldItem: { ...item }
    });
  }
  delClick = (item) => {
    const arr = [...this.state.todoList];
    arr.forEach((t, i) => {
      if (t.id === item.id) {
        arr.splice(i, 1);
      }
    })
    this.setState({ todoList: arr });
  }
  clearCompleted = () => {
    this.setState({
      todoList: this.state.todoList.filter(t => !t.selected)
    });
  }
  editChange = (e, item) => {
    let arr = [...this.state.todoList];
    arr.forEach((t) => {
      if (t.id === item.id) {
        t.content = e.target.value
      }
    });
    this.setState({
      todoList: arr
    })
  }
  editKeyUp = (e, item) => {
    if (e.keyCode === 27) {
      this.setState({
        currentItem: null
      })
    }
    if (e.keyCode === 13) {
      let old = {
        ...this.state.oldItem,
        content: e.target.value
      }
      this.setState({ oldItem: old, currentItem: null });
    }
  }
  editBlur = (e, item) => {
    let arr = [...this.state.todoList];
    arr.forEach((t) => {
      if (t.id === item.id) {
        t.content = this.state.oldItem.content;
      }
    });
    this.setState({
      todoList: arr
    })
  }
  render() {
    return (
      <section className="todoapp">
        <header className="header">
          <h1>todos</h1>
          <input
            className="new-todo"
            placeholder="What needs to be done?"
            autoFocus
            onKeyUp={this.addList}
          />
        </header>
        {
          (() => {
            if (this.state.todoList.length) {
              return (
                <div>
                  <section className="main">
                    <input
                      id="toggle-all"
                      className="toggle-all"
                      type="checkbox"
                      checked={this.allSelected}
                      onChange={(e) => { this.allSelected = !this.allSelected }}
                    />
                    <label htmlFor="toggle-all">Mark all as complete</label>
                    <ul className="todo-list">
                      {
                        this.list.map((item, i) => {
                          return (
                            <li
                              key={i}
                              className={
                                (() => {
                                  let str = '';
                                  if (item.selected) str += 'completed'
                                  if (this.state.currentItem === item) str += ' editing'
                                  return str;
                                })()
                              }
                              onDoubleClick={() => { this.dblClick(item) }}
                            >
                              <div className="view">
                                <input
                                  className="toggle"
                                  type="checkbox"
                                  checked={item.selected}
                                  onChange={(e) => { this.itemChange(e, item) }}
                                />
                                <label>{item.content}</label>
                                <button
                                  className="destroy"
                                  onClick={() => { this.delClick(item) }}
                                ></button>
                              </div>
                              {
                                (() => {
                                  if (item === this.state.currentItem) {
                                    return (
                                      <input
                                        ref="inputOnFocus"
                                        className="edit"
                                        value={item.content}
                                        onChange={(e) => { this.editChange(e, item) }}
                                        onBlur={(e) => { this.editBlur(e, item) }}
                                        onKeyUp={(e) => { this.editKeyUp(e, item) }}
                                      />
                                    );
                                  } else {
                                    return (
                                      <input
                                        className="edit"
                                        value={item.content}
                                        onChange={(e) => { this.editChange(e, item) }}
                                        onBlur={(e) => { this.editBlur(e, item) }}
                                        onKeyUp={(e) => { this.editKeyUp(e, item) }}
                                      />
                                    );
                                  }
                                })()
                              }
                            </li>
                          );
                        })
                      }
                    </ul>
                  </section>
                  <footer className="footer">
                    <span className="todo-count"><strong>{this.leftCount}</strong> item left</span>
                    <ul className="filters">
                      {
                        stateList.map((item, i) => {
                          return (
                            <li key={'a' + i}>
                              <a
                                href="#/1"
                                className={this.state.currentState === item ? 'selected' : ''}
                                onClick={(e) => { e.preventDefault();this.setState({ currentState: item }); }}
                              >{item}</a>
                            </li>
                          );
                        })
                      }
                    </ul>
                    {
                      this.someSelected && (<button
                        className="clear-completed"
                        onClick={this.clearCompleted}
                      >Clear completed</button>)
                    }

                  </footer>
                </div>
              );
            } else {
              return '';
            }
          })()
        }
      </section>
    );
  }
}

export default TodoMVC;